# -*- coding: utf-8 -*-
"""Sphinx configuration file for the TVM Book documentation project.

This file configures the Sphinx build system for generating the TVM Book documentation.
It includes settings for project information, extensions, HTML output, and various
customizations to enhance the documentation experience.
"""

# Standard library imports
import os
import sys
from pathlib import Path

# Platform-specific configurations
if sys.platform == 'win32':
    import asyncio
    asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())

# === Path setup =====================================================================================
# Get the project root directory
ROOT = Path(__file__).resolve().parents[1]
# Extend Python path to include the documentation directory for custom modules
sys.path.extend([str(ROOT/'doc')])

# == Project information =============================================================================
# Project name, author, and copyright information
project = 'flexloopy'  # Project name
author = 'xinetzone'  # Documentation author
copyright = '2022, xinetzone'  # Copyright information

# == Internationalization settings ===================================================================
language = 'zh_CN'  # Documentation language
locale_dirs = ['../locales/']  # Path to translation files
gettext_compact = False  # Create separate .po files for each translation

# == General configuration ===========================================================================
# List of Sphinx extensions to load
# ------------------------------------------------------------------------------------- 
extensions = [
    # Core content processing
    "mystx",  # Markdown and Jupyter notebook support
    "sphinx_design",  # UI components for Sphinx
    "sphinx.ext.viewcode",  # Add links to highlighted source code
    "sphinx.ext.napoleon",  # Support for Google and NumPy style docstrings
    
    # Linking and referencing
    "sphinx.ext.extlinks",  # Shorten external links
    "sphinx.ext.intersphinx",  # Link to other documentation
    
    # UI enhancements
    'sphinx_copybutton',  # Add copy buttons to code blocks
    "sphinx_comments",  # Add comments and annotations to Sphinx docs
]

# Template and file exclusion settings
# -------------------------------------------------------------------------------------
templates_path = ['_templates']  # Paths to template files

exclude_patterns = [  # Patterns to exclude when looking for source files
    "_build",  # Build directory
    "Thumbs.db",  # Windows thumbnail cache
    ".DS_Store",  # macOS directory metadata
]

# Cross-referencing configuration
# ------------------------------------------------------------------------------------- 
intersphinx_mapping = {
    "python": ("https://docs.python.org/3.12", None),  # Python documentation
    "tvm": ("https://xinetzone.github.io/tvm/", None),  # TVM documentation
    "torch": ("https://pytorch.org/docs/stable/", None),  # PyTorch documentation
}

# External link shortcuts
# ------------------------------------------------------------------------------------- 
extlinks = {
    'daobook': ('https://daobook.github.io/%s', 'Daobook %s'),
    'xinetzone': ('https://xinetzone.github.io/%s', 'xinetzone %s'),
}

# Copy button configuration
# -------------------------------------------------------------------------------------
# Exclude copy buttons from notebook cell numbers
copybutton_exclude = '.linenos, .gp'  # Skip all prompts generated by Pygments
copybutton_selector = ":not(.prompt) > div.highlight pre"

# == HTML output configuration =======================================================================
# Theme and basic HTML settings
# ------------------------------------------------------------------------------------- 
html_theme = 'mystx'  # Theme name for HTML output
html_logo = "_static/images/logo.jpg"  # Logo image path
html_title = "TVM 开发指南"  # HTML page title
html_copy_source = True  # Allow copying of source code
html_favicon = "_static/images/favicon.jpg"  # Favicon path
html_last_updated_fmt = '%Y-%m-%d, %H:%M:%S'  # Format for last updated timestamp
# == Comments and annotations ========================================================================
# Add commenting and annotation functionality to the Sphinx site
# ------------------------------------------------------------------------------------- 
comments_config = {
    "hypothesis": True,  # Enable Hypothesis annotation tool
    # "dokieli": True,  # Alternative annotation tool (disabled)
    "utterances": {  # GitHub-based commenting system
        "repo": f"xinetzone/{project}",
        "optional": "config",
    }
}

# == Rich hover tooltips ==============================================================================
# Add rich hover tooltip functionality using Sphinx Tippy
# ------------------------------------------------------------------------------------- 
extensions.append("sphinx_tippy")

# Optional tippy configurations (currently commented out)
tippy_enable_mathjax = True
# tippy_anchor_parent_selector = "div.content"
# tippy_logo_svg = Path("tippy-logo.svg").read_text("utf8")
# tippy_custom_tips = {
#     "https://example.com": "<p>This is a custom tip for <a>example.com</a></p>",
#     "https://atomiks.github.io/tippyjs": (
#         f"{tippy_logo_svg}<p>Using Tippy.js, the complete tooltip, popover, dropdown, "
#         "and menu solution for the web, powered by Popper.</p>"
#     ),
# }

tippy_rtd_urls = [  # URLs for ReadTheDocs documentation with tooltips
    "https://docs.readthedocs.io/en/stable/",
    "https://www.sphinx-doc.org/zh-cn/master/",
]

# == Optional extensions and configurations ===========================================================
# BibTeX references
# ------------------------------------------------------------------------------------- 
extensions.append('sphinxcontrib.bibtex')  # Support for BibTeX references
bibtex_bibfiles = [  # Paths to BibTeX reference databases
    '_static/references/book.bib',
    "_static/references/articles.bib"
]

# API documentation generation
# ------------------------------------------------------------------------------------- 
extensions.append("autoapi.extension")  # Auto-generate API documentation
autoapi_dirs = [f"../python/{project.replace('-', "_")}"]  # Directories to generate API docs from
autoapi_root = "autoapi"  # Root directory for generated API docs
autoapi_generate_api_docs = True  # Enable automatic API doc generation

# Graphviz diagrams
# ------------------------------------------------------------------------------------- 
extensions.append("sphinx.ext.graphviz")  # Support for Graphviz diagrams
graphviz_output_format = "svg"  # Output format for Graphviz diagrams
inheritance_graph_attrs = dict(  # Attributes for inheritance graphs
    rankdir="LR",
    fontsize=14,
    ratio="compress",
)
# GitHub contributors list
# ------------------------------------------------------------------------------------- 
extensions.append('sphinx_contributors')  # Render list of contributors from GitHub
# Thebe configuration for live code execution
# ------------------------------------------------------------------------------------- 
thebe_config = {
    "repository_url": f"https://github.com/xinetzone/{project}",
    "repository_branch": "main",
    "selector": "div.highlight",  # Selector for code blocks to make interactive
    # "selector": ".thebe",
    # "selector_input": "",
    # "selector_output": "",
    # "codemirror-theme": "blackboard",  # Doesn't currently work
    # "always_load": True,  # To load thebe on every page
}
# Open Graph metadata
# ------------------------------------------------------------------------------------- 
# extensions.append("sphinxext.opengraph")  # Add Open Graph metadata for social sharing
# ogp_site_url = f"https://{project}.readthedocs.io/zh-cn/latest/"  # Site URL for Open Graph
# ogp_social_cards = {
#     "site_url": f"{project}lib.readthedocs.io",  # Replace with your actual site URL
#     "image": "_static/images/logo.jpg",  # Social card image (must be PNG or JPEG, not SVG)
#     "font": "WenQuanYi Zen Hei",  # Common Chinese font with better Matplotlib compatibility
#     "line_colors": "#4078c0",  # Line colors for social cards
# }
# Sitemap generation
# ------------------------------------------------------------------------------------- 
extensions.append("sphinx_sitemap")  # Generate sitemaps.org compatible sitemaps
sitemap_url_scheme = "{lang}{version}{link}"  # URL scheme for sitemap entries

# Set base URL based on environment
if not os.environ.get("READTHEDOCS"):
    html_baseurl = os.environ.get("SITEMAP_URL_BASE", "http://127.0.0.1:8000/")
    sitemap_url_scheme = "{link}"
elif os.environ.get("GITHUB_ACTIONS"):
    html_baseurl = os.environ.get("SITEMAP_URL_BASE", "https://xinetzone.github.io/")

sitemap_locales = [None]  # List of languages for sitemap

# Additional configurations
# ------------------------------------------------------------------------------------- 
# List of (type, target) tuples that should be ignored when nitpicking
nitpick_ignore = [
    ("py:class", "docutils.nodes.document"),
    ("py:class", "docutils.parsers.rst.directives.body.Sidebar"),
]

# List of warning types to suppress
# ------------------------------------------------------------------------------------- 
suppress_warnings = [
    # Disable warnings for unknown MIME types in MyST-NB
    "mystnb.unknown_mime_type",
    "mystnb.mime_priority",
    
    # Disable MyST-related warnings
    "myst.xref_missing",
    "myst.domains",
    "myst.newLineInDisplayMode",  # Disable warnings for newlines in display math mode
    
    # Disable reference-related warnings
    "ref.ref",
    
    # Disable AutoAPI-related warnings
    "autoapi.python_import_resolution",
    "autoapi.not_readable",
]

numfig = True  # Enable numbering of figures, tables, and code blocks

# MyST extensions configuration
# ------------------------------------------------------------------------------------- 
myst_enable_extensions = [
    "dollarmath",  # Enable dollar signs for math
    "amsmath",  # Enable amsmath LaTeX environments
    "deflist",  # Enable definition lists
    # "html_admonition",  # Enable HTML admonitions (disabled)
    # "html_image",  # Enable HTML image attributes (disabled)
    "colon_fence",  # Enable code fences using colons
    # "smartquotes",  # Enable smart quotes (disabled)
    "replacements",  # Enable typographic replacements
    # "linkify",  # Enable automatic linking of URLs (disabled)
    "substitution",  # Enable substitution variables
]

# ================================= 版本切换器配置 =================================
version_switcher_json_url = "https://tvm_book.readthedocs.io/zh-cn/latest/_static/switcher.json"

# Custom sidebars
# ------------------------------------------------------------------------------------- 
extensions.append("ablog")
html_sidebars = {
    "reference/blog/*": [
        "navbar-logo.html",
        "search-field.html",
        "ablog/postcard.html",
        "ablog/recentposts.html",
        "ablog/tagcloud.html",
        "ablog/categories.html",
        "ablog/archives.html",
        "sbt-sidebar-nav.html",
    ]
}

# Jupyter notebook execution settings
# ------------------------------------------------------------------------------------- 
nb_execution_excludepatterns = ["test/"]  # Patterns to exclude from notebook execution
nb_execution_mode = "off"  # Notebook execution mode ("off", "cache")

